<?php
namespace backend\components\widget\file;

use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\JsExpression;
use yii\widgets\InputWidget;

/**
 * UploadWidget
 * @property array $uploadOptions
 * @property string $type
 * @property-read \yii\web\JsExpression $uploadSuccess
 * @property-read \yii\web\JsExpression $afterSelected
 * @package backend\components\widget\file
 */
abstract class UploadWidget extends InputWidget
{

    /**
     * @var array
     */
    public $uploadOptions = [];

    /**
     * @var string
     */
    protected $type;

    /**
     * init
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {
        parent::init();

        $this->uploadOptions = array_merge([
            'uploadUrl' => Url::to('/file/upload'),
            'uploadEle' => uniqid(),
            'defaultImage' => '/images/image.png',
            'afterSelected' => $this->getAfterSelected(),
            'uploadSuccess' => $this->getUploadSuccess(),
        ],params('upload')[$this->type]??[],$this->uploadOptions);

        $this->registerJsCode();
    }

    /**
     * run
     * @return string
     */
    public function run()
    {

        $value = $this->hasModel() ? Html::getAttributeValue($this->model, $this->attribute) : $this->value;

        $name = $this->hasModel() ? Html::getInputName($this->model, $this->attribute) : $this->name;

        return $this->render($this->type, [
            'name'    => $name,
            'value'   => $value,
            'options' => $this->options,
            'uploadOptions' => $this->uploadOptions,
        ]);
    }

    /**
     * getAfterSelected
     * @return JsExpression
     */
    public function getAfterSelected()
    {
        $js = "function(file,Upload){
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(arg) {
        Upload.setting.uploadEle.next('img,video').attr('src',arg.target.result).attr('poster','');
    };
    return true;
}";
        return new JsExpression($js);
    }

    /**
     * getUploadSuccess
     * @return JsExpression
     */
    public function getUploadSuccess()
    {
        return new JsExpression('function(res,Upload){$("#'.$this->options['id'].'").val(res.data.fileUrl)}');
    }

    /**
     * registerJsCode
     */
    public function registerJsCode()
    {
        $uploadOptions = $this->uploadOptions;

        $uploadOptions['mimeTypes'] = explode(',',$this->uploadOptions['mimeTypes']??[]);

        $uploadOptions['maxSize'] = $this->uploadOptions['maxSize']??0;

        $uploadOptions = Json::htmlEncode($uploadOptions);

        UploadAsset::register($this->view);

        $js = <<<JS
(new Upload()).init({$uploadOptions}).click();
$('#{$this->options['id']}').next('div.file-delete').click(function() {
  $('#{$this->options['id']}').val('').closest('.file-div-box').find('img,video').attr({poster:'{$this->uploadOptions["defaultImage"]}',src:'{$this->uploadOptions["defaultImage"]}'});
});
JS;

        $this->view->registerJs($js,$this->view::POS_READY);
    }

}